﻿using UnityMethods.Extend;
using SqlSugar;
using System;
using UnityTemplate.ApiModel;
using UnityTemplate.Repository;
using UnityTemplate.Services.Interface;

namespace UnityTemplate.Services.Implement
{
    public class UserService : IUserService
    {
        public ISqlSugarClient Db { private set; get; }

        public UserService(ISqlSugarClient db)
        {
            Db = db;
        }

        public BaseUserInfos GetUserInfo(string userId, string userName)
        {
            return Db.Queryable<BaseUserInfos>().Where(a => a.UserName == userName && a.Id.ToString() == userId).First();
        }

        /// <summary>
        /// 通过用户名和密码获取用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public BaseUserInfos GetUserInfoByPassword(string userName, string password)
        {
            return Db.Queryable<BaseUserInfos>().Where(a => a.UserName == userName && a.Password == password.ToMD5_32()).First();
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public int AddUser(BaseUserInfos user)
        {
            if (user == null) return ApiStatus.FailedToRegister;

            if (!Db.Queryable<BaseUserInfos>().Any(it => it.Account.Equals(user.Account)))
            {
                user.Id = SnowFlakeSingle.Instance.NextId();
                user.Password = user.Password.ToMD5_32();

                return Db.Insertable<BaseUserInfos>(user).ExecuteCommand() != 0 ? ApiStatus.OK : ApiStatus.FailedToRegister;
            }

            return ApiStatus.UserExist;
        }
    }
}
